<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="4">
              <a-form-item label="部门" prop="type">
                <a-tree-select
                  v-model="queryParam.deptId"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="deptOptions"
                  placeholder="请选择"
                  :replaceFields="{
                    children: 'children',
                    title: 'menuName',
                    key: 'id',
                    value: 'id',
                  }"
                  @change="onMenuTreeChange"
                  allow-clear
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="员工">
                <a-select
                  placeholder="请选择员工"
                  v-model="queryParam.userId"
                  :getPopupContainer="
                    (triggerNode) => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="d in userNamesList"
                    :key="d.name"
                    :value="d.id"
                    >{{ d.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="6">
              <a-form-item label="财务确认时间">
                <a-range-picker
                  v-model="dateRange"
                  valueFormat="YYYY-MM-DD"
                  :show-today="true"
                />
              </a-form-item>
            </a-col>

            <a-col>
              <span
                class="table-page-search-submitButtons"
                style="float: right"
              >
                <a-button type="primary" @click="handleQuery"
                  ><a-icon type="search" />查询</a-button
                >
                <a-button style="margin-left: 8px" @click="resetQuery"
                  ><a-icon type="redo" />重置</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <a-tabs :activeKey="tabKey" @change="callback">
        <a-tab-pane key="销售" tab="销售业绩"> </a-tab-pane>
        <a-tab-pane key="客服" tab="客服业绩"> </a-tab-pane>
      </a-tabs>
      <a-table
        rowKey="id"
        :columns="sumcolumns"
        :data-source="sumKpiStatisticList"
        size="middle"
        bordered
        :pagination="false"
      >
        <span slot="amount" slot-scope="text">
          ¥ {{ formatNumber(text) }}
        </span>
        <span slot="counts" slot-scope="text, record">
          <a
            @click="handleShowRecord(record)"
            v-if="text"
            style="font-weight: bold"
          >
            {{ text }}
          </a>
        </span>
        <span slot="yejiCompareLastMonth" slot-scope="record">
          ¥
          {{
            formatNumber(
              record.sumYejiAmountCurMonth - record.sumYejiAmountLastMonth
            )
          }}

          <span
            v-if="
              record.sumYejiAmountCurMonth - record.sumYejiAmountLastMonth > 0
            "
            style="color: green"
          >
            ↑
          </span>

          <span
            v-else-if="
              record.sumYejiAmountCurMonth - record.sumYejiAmountLastMonth < 0
            "
          >
            ↓
          </span>
          <span v-else> </span>
        </span>

        <span slot="counts" slot-scope="text, record">
          <a
            @click="handleShowRecord(record)"
            v-if="text"
            style="font-weight: bold"
          >
            {{ text }}
          </a>
        </span>
      </a-table>

      <a-card :bordered="false" style="overflow-y: auto; padding-top: 15px">
        <advance-table
          :loading="loading"
          rowKey="id"
          :columns="columns"
          :expandedRowKeys="expandedKeys"
          @expand="onExpandCurrent"
          :data-source="bizBillKpiList"
          title="还款信息"
          size="middle"
          tableKey="biz-loanBill-index-table"
          @refresh="getList"
          :format-conditions="true"
          :pagination="{
            current: queryParam.pageNum,
            pageSize: queryParam.pageSize,
            total: total,
            showSizeChanger: true,
            showLessItems: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
            onChange: changeSize,
            onShowSizeChange: onShowSizeChange,
          }"
          :scroll="{ x: '100vh' }"
        >
          <span slot="counts" slot-scope="{ text, record }">
            <a
              @click="handleShowRecord(record)"
              v-if="text"
              style="font-weight: bold"
            >
              {{ text }}
            </a>
          </span>
          <span slot="loanType" slot-scope="{ record }">
            {{ loanTypeFormat(record) }}
          </span>

          <span slot="isOverdue" slot-scope="{ text, record }">
            <template v-if="record.isOverdue == '1'">
              <a-badge status="error" />已逾期
            </template>
            <template v-else> <a-badge status="processing" />未逾期 </template>
          </span>

          <span slot="isPayAll" slot-scope="{ record }">
            <template v-if="record.isPayAll == '1'">
              <a-badge status="success" />已结清
            </template>
            <template v-else> <a-badge status="processing" />未结清 </template>
          </span>

          <span slot="operation" slot-scope="{ text, record }">
            <a
              @click="handleUpdate(record)"
              v-hasPermi="['biz:bizLoanBill:edit']"
            >
              修改
            </a>
          </span>
          <span slot="rowindex" slot-scope="{ index }">
            {{ index + 1 }}
          </span>
          <span slot="amount" slot-scope="{ text }">
            ¥ {{ formatNumber(text) }}
          </span>
          <span slot="yejiCompareLastMonth" slot-scope="{ record }"
            >¥
            {{
              formatNumber(
                record.sumYejiAmountCurMonth - record.sumYejiAmountLastMonth
              )
            }}

            <span
              v-if="
                record.sumYejiAmountCurMonth - record.sumYejiAmountLastMonth > 0
              "
              style="color: green"
            >
              ↑
            </span>

            <span
              v-else-if="
                record.sumYejiAmountCurMonth - record.sumYejiAmountLastMonth < 0
              "
            >
              ↓
            </span>
            <span v-else> </span>
          </span>
        </advance-table>
      </a-card>
    </a-card>
    <a-modal
      :visible="showRecordModal"
      title="业绩明细"
      v-if="showRecordModal"
      @cancel="showRecordModal = false"
      @ok="showRecordModal = false"
      width="1200px"
      :dialog-style="{ top: '20px', heigth: '600px' }"
    >
      <billkpi-record
        v-if="showRecordModal"
        ref="billkpiRecord"
        :userId="userId"
        :type="type"
        @ok="getList"
        @close="showRecordModal = false"
      />
    </a-modal>
  </div>
</template>
<script>
import {
  getSelfKpiStatisticVo,
  getSumKpiStatisticVo,
} from "@/api/biz/bizJinjianKpi";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import { listUser } from "@/api/system/user";
import { listDeptTree } from "@/api/system/dept";

import billkpiRecord from "@/views/biz/statistics/billkpiRecord.vue";
export default {
  name: "BizLoanBill",
  components: {
    AdvanceTable,
    billkpiRecord,
  },
  data() {
    return {
      // 标签页
      tabKey: "销售",
      type: "",
      userId: "",
      showRecordModal: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 个人统计表格数据
      bizBillKpiList: [],
      // 资方合计
      sumKpiStatisticList: [],
      orgTypeOptions: [],
      // 结算类型字典
      typeOptions: [],
      // 结算状态字典
      statusOptions: [],
      dateRange: [],
      productList: [],
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,

        deptId: undefined,

        userName: undefined,

        deptName: undefined,

        jinjianId: undefined,

        cusName: undefined,

        beginQdTime: undefined,

        status: undefined,
      },
      columns: [
        {
          title: "序号",
          dataIndex: "rowindex",
          ellipsis: true,
          align: "center",
          width: "50px",
          scopedSlots: { customRender: "rowindex" },
        },
        {
          title: "姓名",
          dataIndex: "userName",
          align: "center",
          width: "120px",
        },

        {
          title: "签约笔数",
          dataIndex: "jinjianCounts",
          align: "center",
          width: "150px",
          scopedSlots: { customRender: "counts" },
        },

        {
          title: "财务回款金额(元)",
          dataIndex: "sumServiceAmount",
          scopedSlots: { customRender: "amount" },
          align: "right",
          width: "180px",
        },

        {
          title: "业绩(元)",
          dataIndex: "sumYejiAmount",
          ellipsis: true,
          align: "right",
          width: "180px",
          scopedSlots: { customRender: "amount" },
        },

        {
          title: "财务回款金额(当月)",
          dataIndex: "sumServiceAmountCurMonth",
          scopedSlots: { customRender: "amount" },
          align: "right",
          width: "180px",
        },
        {
          title: "财务回款金额(上月)",
          dataIndex: "sumServiceAmountLastMonth",
          scopedSlots: { customRender: "amount" },
          align: "right",
          width: "180px",
        },
        {
          title: "业绩(当月)",
          dataIndex: "sumYejiAmountCurMonth",
          scopedSlots: { customRender: "amount" },
          align: "right",
          width: "180px",
        },

        {
          title: "业绩(上月)",
          dataIndex: "sumYejiAmountLastMonth",
          scopedSlots: { customRender: "amount" },
          align: "right",
          width: "180px",
        },
        {
          title: "业绩环比",
          scopedSlots: { customRender: "yejiCompareLastMonth" },
          align: "right",
          width: "180px",
        },
      ],
      sumcolumns: [
        {
          title: "",
          ellipsis: true,
          dataIndex: "heji",
          align: "center",
          width: "50px",
        },
        {
          title: "签约笔数",
          dataIndex: "jinjianCounts",
          align: "center",
          width: "150px",
          scopedSlots: { customRender: "counts" },
        },

        {
          title: "业绩(元)",
          dataIndex: "sumYejiAmount",
          ellipsis: true,
          align: "right",
          width: "180px",
          scopedSlots: { customRender: "amount" },
        },

        {
          title: "业绩(当月)",
          dataIndex: "sumYejiAmountCurMonth",
          scopedSlots: { customRender: "amount" },
          align: "right",
          width: "180px",
        },

        {
          title: "业绩(上月)",
          dataIndex: "sumYejiAmountLastMonth",
          scopedSlots: { customRender: "amount" },
          align: "right",
          width: "180px",
        },
        {
          title: "业绩环比",
          scopedSlots: { customRender: "yejiCompareLastMonth" },
          align: "right",
          width: "180px",
        },
      ],
      // 根据岗位删选员工
      postIds: ["gwzg", "rzgw", "qyjl", "sg"],
      // 部门信息
      deptOptions: [],
      userNamesList: [],
      isKefu: 2,
      expandedKeys: [],
    };
  },
  created() {
    this.getList();
    this.getDicts("zifang_jiesuan_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("zifang_jiesuan_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("org_type_options").then((response) => {
      this.orgTypeOptions = response.data;
    });
    this.getDeptList();
  },
  methods: {
    /** tab选显卡操作 */
    callback(v) {
      this.tabKey = v;
      this.queryParam.deptId = undefined;
      this.queryParam.userId = undefined;
      this.userNamesList = undefined;
      if (v === "客服") {
        this.isKefu = "1";
        this.postIds = undefined;
      } else {
        this.isKefu = "2";
        this.postIds = ["gwzg", "rzgw", "qyjl", "sg"];
      }
      this.resetQuery();
    },
    handleShowRecord(record) {
      this.showRecordModal = true;
      console.log("查看记录", record);
      if (this.tabKey === "销售") {
        this.userId = record.userId;
      } else {
        this.userId = undefined;
      }

      this.type = this.tabKey;
    },

    onMenuTreeChange(value) {
      this.getUserList(value);
    },
    getUserList(deptId) {
      const params = {
        pageNum: 1,
        pageSize: 100,
        deptId: deptId,
      };
      if (this.isKefu) {
        params.isKefu = this.isKefu;
      }
      if (this.postIds) {
        params.postIds = this.postIds;
      }
      listUser(params).then((res) => {
        this.userNamesList = res.data.list;
      });
    },
    getDeptList() {
      listDeptTree("", 3).then((response) => {
        // this.expandTree(response.data, 3, this.expandedRowKeys);
        this.deptOptions = response.data;
      });
    },
    formatNumber(num) {
      return parseFloat(num || 0).toFixed(2);
    },
    onExpandCurrent(expandedKeys, row) {
      if (expandedKeys) {
        this.expandedKeys = [row.id];
      } else {
        this.expandedKeys = [];
      }
    },
    getList() {
      this.queryParam.queryType = this.tabKey;
      this.loading = true;
      console.log("this.queryParam", this.queryParam);
      getSelfKpiStatisticVo(
        this.addDateRange(this.queryParam, this.dateRange)
      ).then((response) => {
        this.bizBillKpiList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
      getSumKpiStatisticVo(
        this.addDateRange(this.queryParam, this.dateRange)
      ).then((response) => {
        this.sumKpiStatisticList = [];
        var data = response.data;
        data.heji = "合计：";
        this.sumKpiStatisticList.push(data);
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
      };
      this.handleQuery();
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = size;
      this.getList();
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
  },
};
</script>
